using System.Runtime.InteropServices;

namespace MultiAgentsClient.Tools;

public static class ClipboardTool
{
    [DllImport("user32.dll")]
    private static extern nint OpenClipboard(nint hWndNewOwner);

    [DllImport("user32.dll")]
    private static extern bool CloseClipboard();

    [DllImport("user32.dll")]
    private static extern nint GetClipboardData(uint uFormat);

    [DllImport("user32.dll")]
    private static extern bool IsClipboardFormatAvailable(uint format);

    [DllImport("kernel32.dll")]
    private static extern nint GlobalLock(nint hMem);

    [DllImport("kernel32.dll")]
    private static extern bool GlobalUnlock(nint hMem);

    [DllImport("kernel32.dll")]
    private static extern int GlobalSize(nint hMem);

    private const uint CF_HDROP = 15;

    public static List<string> GetClipboardFilePaths()
    {
        List<string> filePaths = [];

        if (IsClipboardFormatAvailable(CF_HDROP))
        {
            OpenClipboard(nint.Zero);
            try
            {
                nint data = GetClipboardData(CF_HDROP);
                if (data != nint.Zero)
                {
                    nint fileList = GlobalLock(data);
                    if (fileList != nint.Zero)
                    {
                        try
                        {
                            int fileCount = Marshal.ReadInt32(fileList);
                            nint fileNamePtr = nint.Add(fileList, Marshal.SizeOf(typeof(int)));

                            for (int i = 0; i < fileCount; i++)
                            {
                                string? filePath = Marshal.PtrToStringAuto(fileNamePtr);
                                if (filePath != null)
                                {
                                    if (IsValidFilePath(filePath))
                                    {
                                        filePaths.Add(filePath);
                                    }
                                    fileNamePtr = nint.Add(fileNamePtr, filePath.Length * 2 + 2);
                                }
                            }
                        }
                        finally
                        {
                            GlobalUnlock(data);
                        }
                    }
                }
            }
            finally
            {
                CloseClipboard();
            }
        }

        return filePaths;
    }

    private static bool IsValidFilePath(string filePath)
    {
        return !string.IsNullOrWhiteSpace(filePath) &&
               Path.IsPathRooted(filePath) &&
               File.Exists(filePath);
    }
}
